use get_if_addrs::get_if_addrs;
use std::net::Ipv4Addr;

pub fn shell_escape(input: &str) -> String {
    let mut output = String::with_capacity(input.len() + 4);
    for c in input.chars() {
        match c {
            '"' => output.push_str("\\\""),
            '\\' => output.push_str("\\\\"),
            _ => output.push(c),
        }
    }
    output
}

pub fn probe_interface_ip() -> (String, Ipv4Addr) {
    let mut local_name = String::from("lo");
    if let Ok(ifces) = get_if_addrs() {
        for ifce in ifces.iter() {
            if let std::net::IpAddr::V4(ip) = ifce.ip() {
                if !ifce.is_loopback() && ifce.name != "lo" {
                    return (ifce.name.clone(), ip);
                }
                if ifce.is_loopback() {
                    if local_name.is_empty() {
                        local_name = ifce.name.clone();
                    }
                }
            }
        }
    }
    (local_name, Ipv4Addr::LOCALHOST)
}
